package com.itheima.service.impl;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.dto.LoginDTO;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 手机验证码登录
     * @param loginDTO
     * @return
     */
    @Override
    public Result login(LoginDTO loginDTO) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String telephone = loginDTO.getTelephone();  // 手机号
        String codeInRedis = valueOperations.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN).toString(); // redis中缓存的验证码
        String validateCode = loginDTO.getValidateCode(); // 用户输入的验证码
        // 先做非空判断 手机号和验证码都不能为空
        if (telephone == null || telephone.isEmpty() || validateCode == null || validateCode.isEmpty()){
            return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL, null);
        }
        if (codeInRedis != null && validateCode.equals(codeInRedis)){
            // 验证码正确
            return new Result(true, MessageConstant.LOGIN_SUCCESS, null);
        }else{
            // 验证码错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR, null);
        }
    }
}
